# -*- coding: utf-8 -*-
import subprocess
import commands
def makepdf(S,filename='all',comments={},folder="results/091026-OPE3",author="Jeppe Fock",title="MCBJ",width='0.9',filestarts='',fileends=['_brake','_make']):
  body="\section{%s} " % folder.replace('_','\_') 
  body +="\n\n"
  if type(filestarts)==type(''):
    filestarts = [filestarts]
  for s in S:
    body += r"""\subsection{%s} """ % s.replace('_','\_')
    body +="\n\n"
    for ff in fileends:
      for fs in filestarts:
        if width>1:
	  body += r"\hspace{-%s\textwidth}" % ((float(width)-1)/2.)
        body += r"""
        \includegraphics[width=%s\textwidth]{%s%s%s.png}
        """ % (width,fs,s,ff)
        body +="\n\n"
      if comments.has_key(s):
        body += comments[s]
        body += "\n\n"
  return  __makepdf__(body,filename=filename,folder=folder,author=author,title=title)


def __makepdf__(text,filename='all',folder="results/091026-OPE3",author="Jeppe Fock",title="MCBJ"):
  header = r"""
  \documentclass[a4paper,11pt]{article}
        \usepackage[utf8]{inputenc}
        \usepackage[english]{babel}
        \usepackage{a4}
        \usepackage{graphicx}
        \usepackage[left=1cm,right=1cm,top=1cm,bottom=2cm]{geometry}
  \title{%s}
  \author{%s}
  \graphicspath{{%s}}
  \begin{document}
  """ % (title,author,folder)
  header += text
  header += r"""
  \end{document}"""
  ofile = file("%s/%s.tex" % (folder,filename),'w')
  ofile.write(header)
  ofile.close()
  cmd2 = subprocess.Popen(["pdflatex", "-interaction", "nonstopmode", filename ], cwd=folder, env={"PATH": "/bin:/usr/bin"}, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'),close_fds=True).pid
  return cmd2
  #return commands.getstatusoutput("pdflatex -interaction nonstopmode -output-directory %s %s/%s.tex" % (folder,folder,filename))
